from time import sleep
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 初始化驱动
service = Service(r"D:/chrome_driver/chromedriver.exe")
driver = webdriver.Chrome(service=service)
driver.get('https://hmshop-test.itheima.net/Home/user/login.html')
action = ActionChains(driver)
driver.maximize_window()
driver.implicitly_wait(30)

# 登录
driver.find_element(By.ID,'username').send_keys('15344591092')
driver.find_element(By.ID,'password').send_keys('lyw583580')
driver.find_element(By.ID,'verify_code').send_keys('8888')


# 核心改进1：用JS强制点击（避免之前的遮挡问题）+ 显式等待按钮存在
login_btn = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.XPATH, ".//*[@id='loginform']/div/div[6]/a"))
)
driver.execute_script("arguments[0].click();", login_btn)

# 登录后等待页面跳转/加载完成（关键解决会话失效）
# 等待首页链接可点击，确认会话正常
WebDriverWait(driver, 15).until(
    EC.element_to_be_clickable((By.LINK_TEXT, "首页"))
)

# 首页操作
driver.find_element(By.LINK_TEXT,"首页").click()

# 滚动条
js = "window.scrollTo(0,1000)"
driver.execute_script(js)
sleep(2)


# 下单
driver.find_element(By.XPATH,"html/body/div[5]/div[2]/div[2]/a[1]").click()
driver.refresh()
# 版本
driver.find_element(By.ID,"goods_spec_a_10").click()
# 颜色
driver.find_element(By.ID,"goods_spec_a_13").click()
# 类型
driver.find_element(By.ID,"goods_spec_a_17").click()
# 数量
driver.find_element(By.CSS_SELECTOR,".add").click()
# 加入购物车
driver.find_element(By.CSS_SELECTOR,"#join_cart").click()

driver.switch_to.frame("layui-layer2")
driver.find_element(By.CSS_SELECTOR,".").click()



sleep(100)
driver.quit()